import React from 'react'
import PropTypes from 'prop-types'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Select, message, DatePicker, InputNumber, Input, Upload, Button } from 'antd'
import _ from 'loadsh'
import { UploadOutlined } from '@ant-design/icons'
import { Line, Cell, Split } from '@components/ApprovePre/Approve'
import TextArea from 'antd/lib/input/TextArea'
import { getUploadProps, strToNum } from '@js/tool'
import Text from '@components/Text'

const { Item } = Form
const { Option } = Select

class StepFiveInput extends Component {
  state = {
    dictionaries: {},
    keyTitleMap: {},
    fileList: []
  }

  initKeyTitleMap () {
    const map = {}
    const list = _.get(this.props.instance || {}, 'currentStep.vars', [])
    list.forEach(li => {
      map[li.key] = li.title
    })
    this.setState({
      keyTitleMap: map
    })
  }

  // 获取完整key值
  getKey (key) {
    const { preKey } = this.props
    return `${preKey}_${key}`
  }

  // 获取枚举的字典值
  getDictionary () {
    this.$get('/api/xapc/dictionary', {
      types: '交费情况'
    }).then(res => {
      if (res.status === 1) {
        // 设置枚举字典
        const dictionaries = this.formatDictionaries(res.data)
        this.setState({
          dictionaries
        })
      } else {
        message.error(res.message)
      }
    })
  }

  // 格式化枚举字典
  formatDictionaries (dictionaries = []) {
    const result = {}
    dictionaries.forEach(d => {
      result[d.type] = d.list
    })
    return result
  }

  // 改变实际支付人
  changeParty (id) {
    const { partys } = this.props
    for (let i = 0; i < partys.length; i++) {
      if (partys[i].id === id) {
        this.props.formRef.current.setFieldsValue({
          [this.getKey('payer_actual')]: JSON.stringify(partys[i])
        })
        break
      }
    }
  }

  changeFee () {
    const k = this.getKey.bind(this)
    const c = this.props.formRef.current
    if (c === null) {
      return false
    }
    const o = c.getFieldsValue()
    c.setFieldsValue({
      [k('pay_amount')]: strToNum(o[k('fee_acceptance')]) + strToNum(o[k('fee_processing')])
    })
  }

  componentDidUpdate (prev) {
    if (this.props.instance !== prev.instance) {
      this.initKeyTitleMap()
    }
  }

  componentDidMount () {
    this.getDictionary()
    this.initKeyTitleMap()
  }

  renderReason () {
    const { keyTitleMap } = this.state
    const layout = { labelCol: { flex: '100px' } }
    const k = this.getKey.bind(this)
    if (!keyTitleMap[k('bill_description')]) {
      return null
    }
    return (
      <Line>
        <Cell style={{ width: '65%' }}>
          <Item {...layout} name={k('bill_description')} label={keyTitleMap[k('bill_description')]}>
            <TextArea rows={3} placeholder={`请输入${keyTitleMap[k('bill_description')]}`} />
          </Item>
        </Cell>
      </Line>
    )
  }

  render () {
    const { keyTitleMap, dictionaries } = this.state
    const k = this.getKey.bind(this)
    const isPayType = dictionaries['交费情况'] || []
    const layout = { labelCol: { flex: '108px' } }
    return (
      <div>
        <Line>
          <Cell>
            <Item {...layout} name={k('ispay')} label={keyTitleMap[k('ispay')]} rules={[{ required: true, message: `请选择${keyTitleMap[k('ispay')]}` }]}>
              <Select placeholder={`请选择${keyTitleMap[k('ispay')]}`} allowClear>
                {isPayType.map(li => (
                  <Option key={li.title} value={li.value} title={li.title}>{li.title}</Option>
                ))}
              </Select>
            </Item>
          </Cell>
          <Split />
          <Cell>
            <Item {...layout} name={k('pay_datetime')} label={keyTitleMap[k('pay_datetime')]} rules={[{ required: true, message: `请选择${keyTitleMap[k('pay_datetime')]}` }]}>
              <DatePicker placeholder={`请选择${keyTitleMap[k('pay_datetime')]}`} style={{ width: '100%' }} />
            </Item>
          </Cell>
          <Split />
          <Cell>
            <Item {...layout} name={k('platform_serialno')} label={keyTitleMap[k('platform_serialno')]}>
              <Input placeholder={`请输入${keyTitleMap[k('platform_serialno')]}`} style={{ width: '100%' }} />
            </Item>
          </Cell>
        </Line>
        <Line>
          <Cell>
            <Item {...layout} name={k('pay_amount')} label={keyTitleMap[k('pay_amount')]} rules={[{ required: true, message: `${keyTitleMap[k('pay_amount')]}不能为空` }]}>
              <Text />
            </Item>
          </Cell>
          <Split />
          <Cell>
            <Item {...layout} name={k('fee_acceptance')} label={keyTitleMap[k('fee_acceptance')]} rules={[{ required: true, message: `${keyTitleMap[k('fee_acceptance')]}不能为空` }]}>
              <InputNumber placeholder={`请输入${keyTitleMap[k('fee_acceptance')]}`} style={{ width: '100%' }} onChange={v => this.changeFee()} />
            </Item>
          </Cell>
          <Split />
          <Cell>
            <Item {...layout} name={k('fee_processing')} label={keyTitleMap[k('fee_processing')]} rules={[{ required: true, message: `${keyTitleMap[k('fee_processing')]}不能为空` }]}>
              <InputNumber placeholder={`请输入${keyTitleMap[k('fee_processing')]}`} style={{ width: '100%' }} onChange={v => this.changeFee()} />
            </Item>
          </Cell>
        </Line>
        <Line>
          <Cell>
            <Item noStyle name={k('payer_actual')}><span /></Item>
            <Item {...layout} label={keyTitleMap[k('payer_actual')]}>
              <Select placeholder={`请选择${keyTitleMap[k('payer_actual')]}`} allowClear onChange={v => this.changeParty(v)}>
                {this.props.partys.map(li => (
                  <Option key={li.id} value={li.id} title={li.name}>{li.name}</Option>
                ))}
              </Select>
            </Item>
          </Cell>
          <Split />
          <Cell>
            <Item {...layout} name={k('bill_remark1')} label={keyTitleMap[k('bill_remark1')]}>
              <Input placeholder={`请输入${keyTitleMap[k('bill_remark1')]}`} />
            </Item>
          </Cell>
          {/* <Split />
          <Cell>
            <Item {...layout} name={k('docket_datetime')} label={keyTitleMap[k('docket_datetime')]} rules={[{ required: true, message: `${keyTitleMap[k('docket_datetime')]}不能为空` }]}>
              <DatePicker placeholder={`请选择${keyTitleMap[k('docket_datetime')]}`} style={{ width: '100%' }} />
            </Item>
          </Cell> */}
        </Line>
        {this.renderReason()}
        <Line>
          <Cell style={{ width: '65%' }}>
            <Item {...layout} name='file' label={keyTitleMap[k('pay_fileid')]}>
              <Upload {...getUploadProps.call(this, this.props.formRef)}>
                <Button disabled={this.state.fileList.length > 9}>
                  <UploadOutlined /> 上传文件
                </Button>
              </Upload>
            </Item>
          </Cell>
        </Line>
      </div>
    )
  }
}

StepFiveInput.proptypes = {
  caseDetail: PropTypes.object,
  userInfo: PropTypes.object,
  instance: PropTypes.object,
  formRef: PropTypes.object,
  dictionaries: PropTypes.object,
  claimMap: PropTypes.object,
  preKey: PropTypes.string,
  isChange: PropTypes.bool,
  partys: PropTypes.array,
  claim: PropTypes.object
}

StepFiveInput.defaultProps = {
  caseDetail: {},
  userInfo: {},
  instance: {},
  formRef: {},
  dictionaries: {},
  claimMap: {},
  preKey: '',
  isChange: true,
  partys: [],
  claim: {}
}

const mapState = mapStateToProps(function (state) {
  return {

  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(StepFiveInput)
